package com.example.demo.common;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.example.common.RpcRequest;
import com.example.common.RpcResponse;
import com.example.demo.User;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.HashMap;

public class ProxyHandler {


    public static <T> T create(String server, Class<T> className){
        return (T) Proxy.newProxyInstance(ProxyHandler.class.getClassLoader(), new Class[]{className},  new InvoHandler(server, className));
    }



    public static class InvoHandler implements InvocationHandler {

        private String url ;
        private Class className ;


        public <T> InvoHandler(String server, Class<T> className) {
            this.url = url;
            this.className = className;
        }


        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            before();
            RpcRequest rpcRequest = new RpcRequest(className.getName(), method.getName(), objects);

            String result = HttpRequest.post("http://127.0.0.1:8080/call")
                    .body(JSONUtil.toJsonStr(rpcRequest))
                    .execute().body();
            RpcResponse rpcResponse = JSONUtil.toBean(result, RpcResponse.class);
            after();
            return JSONUtil.toBean(rpcResponse.getData().toString(), method.getReturnType());
        }


        // 调用invoke方法之前执行
        private void before() {
            System.out.println(String.format("log start time [%s] ", new Date()));
        }
        // 调用invoke方法之后执行
        private void after() {
            System.out.println(String.format("log end time [%s] ", new Date()));
        }


    }


}
